package com.yiwyn.utils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {

    /**
     * 加密算法
     */
    private static final String KEY_ALGORITHM = "RSA";
    /**
     * 签名算法
     */
    private static final String RSA_SIGNATURE_ALGORITHM = "SHA1withRSA";


    /**
     * RSA最大加密明文大小-分段加密用
     */
    private static final int MAX_ENCRYPT_BLOCK = 245;
    /**
     * RSA最大解密密文大小-分段解密用
     */
    private static final int MAX_DECRYPT_BLOCK = 256;


    /**
     * 获取公钥publicKey对象
     */
    public static PublicKey getPublicKey(String publicKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] publicKeyByte = decryptBASE64(publicKeyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByte);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }


    /**
     * 获取私钥privateKey对象
     */
    public static PrivateKey getPrivateKey(String privateKeyString) throws Exception {
        byte[] privateKeyByte = decryptBASE64(privateKeyString);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyByte);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }


    /**
     * 正常情况下，publicKey，privateKey都是经过base64编码过的，所以进行密钥处理前需要解码
     * *在获取publicKey、privateKey对象时需要使用
     * BASE64解码 返回字节数组
     * key 需要解码的字符串
     */
    public static byte[] decryptBASE64(String key) {
        return Base64.getDecoder().decode(key);
    }

    /**
     * BASE64编码返回加密字符串
     * bytes 需要编码的字节数组
     */
    private static String encryptBASE64(byte[] bytes) throws Exception {
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 公钥加密
     */
    public static String encrypto(String text, String publicKeyStr) {
        try {
            System.out.println("明文lenth为" + text.length());
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKeyStr));
            byte[] tempBytes = cipher.doFinal(text.getBytes());
            String secretText = encryptBASE64(tempBytes);
            return secretText;
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + text + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     *
     * @param secretText
     */
    public static String decrypto(String secretText, String privateKeyStr) {
        try {
            //生成公钥
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyStr));
            // 密文解码
            byte[] secretText_decode = decryptBASE64(secretText);
            byte[] tempBytes = cipher.doFinal(secretText_decode);
            String text = new String(tempBytes);
            return text;
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + secretText + "]时遇到异常", e);
        }
    }


    /**
     * 公钥加密-分段加密
     */
    public static String encrypt(String plainText, String publicKeyStr) throws Exception {
        System.out.println("明文lenth为" + plainText.length());
        byte[] plainTextArray = plainText.getBytes();
        PublicKey publicKey = getPublicKey(publicKeyStr);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = plainTextArray.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        int i = 0;
        byte[] cache;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(plainTextArray, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(plainTextArray, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptText = out.toByteArray();
        out.close();
        return Base64.getEncoder().encodeToString(encryptText);
    }

    /**
     * 私钥解密-分段解密
     */
    public static String decrypt(String encryptTextHex, String privateKeyStr) throws Exception {
        byte[] encryptText = Base64.getDecoder().decode(encryptTextHex);
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        int inputLen = encryptText.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptText, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] plainText = out.toByteArray();
        out.close();
        return new String(plainText);
    }


    /**
     * 客户端-私钥签名
     */
    public static String sign(String data, String clientPrivateKey) throws Exception {
        PrivateKey privateKey = getPrivateKey(clientPrivateKey);
        Signature signature = Signature.getInstance(RSA_SIGNATURE_ALGORITHM);
        signature.initSign(privateKey);
        byte[] bytes = data.getBytes();
        signature.update(bytes);
        byte[] sign1 = signature.sign();
        return Base64.getEncoder().encodeToString(sign1);
    }

    /**
     * 服务端-使用客户端公钥验签
     */
    public static Boolean signVerify(String data, String signValue, String clientPublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
        PublicKey publicKey = getPublicKey(clientPublicKey);
        Signature signature = Signature.getInstance(RSA_SIGNATURE_ALGORITHM);
        signature.initVerify(publicKey);
        byte[] bytes = data.getBytes();
        signature.update(bytes);
        byte[] bytes1 = decryptBASE64(signValue);
        return signature.verify(bytes1);
    }


}
